package com.springboot.autoconfigure.oss.service.impl;

import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.springboot.autoconfigure.oss.config.OssConfigPropertis;
import com.springboot.autoconfigure.oss.config.PublicMetaConfig;
import com.springboot.autoconfigure.oss.config.QiNiuOSSPropertis;
import com.springboot.autoconfigure.oss.model.FileInfo;
import com.springboot.autoconfigure.oss.model.FileOssOperationStatus;
import com.springboot.autoconfigure.oss.model.FileUploadStatus;
import com.springboot.autoconfigure.oss.service.AbstractInitClientServer;
import com.springboot.autoconfigure.oss.service.OssApiService;
import lombok.NoArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 七牛云文件上传服务
 */
public class QiNiuOssApiServiceImpl implements OssApiService<QiNiuOSSPropertis>, AbstractInitClientServer<String>, InitializingBean {

    Configuration cfg=null;
    Auth auth=  null;
    BucketManager bucketManager=null;

    private QiNiuOSSPropertis qiNiuOSSPropertis;
    private OssConfigPropertis ossConfigPropertis;




    public QiNiuOssApiServiceImpl(QiNiuOSSPropertis qiNiuOSSPropertis, OssConfigPropertis ossConfigPropertis) {
        this.qiNiuOSSPropertis = qiNiuOSSPropertis;
        this.ossConfigPropertis = ossConfigPropertis;
    }


    @Override
    public FileUploadStatus uploadFile(URL url) {
        return null;
    }

    @Override
    public FileUploadStatus uploadFile(URL url, String filePrix) {
        return null;
    }

    @Override
    public FileUploadStatus uploadFile(File file)  {
        return getFileUploadStatus(file,null);
    }

   

    private FileUploadStatus getFileUploadStatus(File file,String filePath) {
        UploadManager uploadManager = getUploadManager();
        DefaultPutRet putRet=null;
        try {
            StringBuilder strBuilder = new StringBuilder();
            if (!StrUtil.isBlank(ossConfigPropertis.getFolderPathName())){
                strBuilder.append(ossConfigPropertis.getFolderPathName());
                strBuilder.append(PublicMetaConfig.FILEPATH_SPLITMARK);
            }
            if (!StrUtil.isBlank(ossConfigPropertis.getFilePrefix())){
                strBuilder.append(ossConfigPropertis.getFilePrefix());
                // 文件名分割符
                strBuilder.append(ossConfigPropertis.getFilePathSplit());
            }
            String fileName= cn.hutool.core.lang.UUID.randomUUID().toString();
            strBuilder.append(fileName);
            Response response = uploadManager.put(file, strBuilder.toString(), getinit());
            putRet= new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        FileUploadStatus fileUploadStatus = FileUploadStatus.suceess();
        fileUploadStatus.setFileKey(putRet.key);
        return fileUploadStatus;
    }

    private UploadManager getUploadManager() {
        Configuration cfg = new Configuration(Region.huadongZheJiang2());
        UploadManager uploadManager = new UploadManager(cfg);
        return uploadManager;
    }

    @Override
    public FileUploadStatus findFileByKey(String fileKey) {
        DownloadUrl url = new DownloadUrl(qiNiuOSSPropertis.getDomain(), qiNiuOSSPropertis.isUseHttps(), fileKey);
//        url.setAttname(attname) // 配置 attname
//                .setFop(fop) // 配置 fop
//                .setStyle(style, styleSeparator, styleParam) ;// 配置 style
        FileUploadStatus suceess = FileUploadStatus.suceess();
        try {
            suceess.setUrlIsPublic(true);
            suceess.setUrl(url.buildURL());
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return suceess;
    }

    @Override
    public FileUploadStatus uploadAbsoulteFilePath(File file, String filePath) {
        if (Strings.isBlank(filePath)){
            throw  new  IllegalArgumentException("filepath must not null");
        }
//        bucketManager.createFileListIterator(qiNiuOSSPropertis.getBucket(),filePath);
        UploadManager uploadManager = getUploadManager();
        DefaultPutRet putRet=null;
        try {
            Response response = uploadManager.put(file, filePath+File.separator+ UUID.randomUUID(), getinit());
            putRet= new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        FileUploadStatus fileUploadStatus = FileUploadStatus.suceess();
        fileUploadStatus.setFileKey(putRet.key);
        return fileUploadStatus;
//        return null;

    }

    @Override
    public FileUploadStatus uploadFile(File file, String fileName) {
        return null;
    }

    @Override
    public FileUploadStatus uploadFileAndCallBack(File file, String callbackUrl) {
        return null;
    }

    @Override
    public List<String> findFile(String... fileNames) {
        return null;
    }

    @Override
    public FileOssOperationStatus delFile(String... fileNames) {

        List<String> suceessKey = null;
        for (String fileName : fileNames) {
            try {
                bucketManager.delete(this.qiNiuOSSPropertis.getBucket(), fileName);
                suceessKey = new ArrayList<String>();
                suceessKey.add(fileName);
            } catch (QiniuException e) {
                e.printStackTrace();
            }
        }
        return FileOssOperationStatus.suceessData(suceessKey);
    }

    /**
     * TODO 待处理 测试失败
     * @param prefix
     * @param limit
     * @return
     */
    @Override
    public List<FileInfo> getBucketSpaceFile(String prefix, int limit) {
        Configuration cfg = new Configuration(Zone.zone0());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(this.qiNiuOSSPropertis.getBucket(), prefix, limit, "");
        List<FileInfo> returnList=new ArrayList<>();
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            com.qiniu.storage.model.FileInfo[] items = fileListIterator.next();
            for (com.qiniu.storage.model.FileInfo item : items) {
                 FileInfo fileInfo = new FileInfo();
                fileInfo.setFileKey(item.key);
                returnList.add(fileInfo);
            }
        }
        return returnList;
    }

    @Override
    public String getinit() {
       return  auth.uploadToken(this.qiNiuOSSPropertis.getBucket());
    }


    @Override
    public void afterPropertiesSet() {
        cfg = new Configuration(Region.huadongZheJiang2());
        auth = Auth.create(this.qiNiuOSSPropertis.getAccessKey(), this.qiNiuOSSPropertis.getSecretKey());
        bucketManager = new BucketManager(auth, cfg);
    }
}
